package com.hzt.agprosaleplatform.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.hzt.agprosaleplatform.common.CustomResponse;
import com.hzt.agprosaleplatform.entity.*;
import com.hzt.agprosaleplatform.mapper.GoodsMapper;
import com.hzt.agprosaleplatform.mapper.ShopMapper;
import com.hzt.agprosaleplatform.service.GoodsService;
import com.hzt.agprosaleplatform.utils.OssUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.sql.Timestamp;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
import java.util.stream.Collectors;

@Slf4j
@Service
public class GoodsServiceImpl implements GoodsService {
    @Autowired
    GoodsMapper goodsMapper;

    @Autowired
    @Qualifier("taskExecutor")
    private Executor taskExecutor;

    @Autowired
    private OssUtil ossUtil;

    @Value("${oss.bucketUrl}")
    private String OSS_BUCKET_URL;
    @Autowired
    private ShopMapper shopMapper;

    @Override
    public List<Good> selectAll() {
        return goodsMapper.selectPage(new Page<>(1, 10), null).getRecords();
    }

    @Override
    public List<Good> selectByCategory(String category){
        return goodsMapper.selectByCategory(category);
    }

    /**
     * 根据品类做分页
     * @param category
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public IPage<Good> PageForCategory(String category, int pageNum, int pageSize) {
        Page<Good> page = new Page<>(pageNum, pageSize);
        return goodsMapper.pageForCategory(page, category);
    }

    @Override
        public Good selectGoodsByGId(Integer gid) {
        return goodsMapper.selectById(gid);
    }

    @Override
    public List<Good> searchGoods(String keyword) {
        QueryWrapper<Good> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(StringUtils.isNotBlank(keyword), "title", keyword)
                   .or()
                   .like(StringUtils.isNotBlank(keyword), "category", keyword);
        return goodsMapper.selectList(queryWrapper);
    }

    @Override
    public IPage<Good> searchGoodsPage(String keyword, int pageNum, int pageSize) {
        Page<Good> page = new Page<>(pageNum, pageSize);
        QueryWrapper<Good> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(StringUtils.isNotBlank(keyword), "title", keyword)
                   .or()
                   .like(StringUtils.isNotBlank(keyword), "category", keyword);
        return goodsMapper.selectPage(page, queryWrapper);
    }

    @Override
    public detailedGoods selectDetailedGoodsByGId(Integer gid) {
        try {
            detailedGoods goods = goodsMapper.selectDetailedGoodsByGId(gid);
            if (goods != null && goods.getGoodsImgStr() != null) {
                // 处理
                String imgUrls = goods.getGoodsImgStr();
                String tags = goods.getTagsStr();

                //切割查回来的字符串，去除逗号
                if (!imgUrls.isEmpty()&&!tags.isEmpty()) {
                    List<String> imgList = new ArrayList<>(Arrays.asList(imgUrls.split(",")));
                    List<String> tagsList = Arrays.asList(tags.split(","));

                    imgList = imgList.stream()
                                   .map(String::trim)
                                   .collect(Collectors.toList());

                    tagsList = tagsList.stream()
                            .map(String::trim)
                            .toList();


                    goods.setGoodsImg(imgList);
                    goods.setTags(tagsList);

                }
            }
//            goods.setShopId(shopMapper.selectById(gid).getShopId());   //必不为空，gid又商品展示页提供
            return goods;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public List<CategoryTree> getCategoryTree() {
        // 一次性查询所有分类数据
        List<GoodsCategory> allCategories = goodsMapper.selectAllCategories();

        // 使用Map存储所有分类，key为code，value为对应的CategoryTree对象
        Map<String, CategoryTree> categoryMap = new HashMap<>();

        // 创建根节点列表
        List<CategoryTree> rootList = new ArrayList<>();

        // 第一次遍历：创建所有节点
        for (GoodsCategory category : allCategories) {
            CategoryTree node = new CategoryTree();
            node.setLabel(category.getCategory_name());
            node.setValue(category.getCode());
            node.setChildren(new ArrayList<>());

            categoryMap.put(category.getCode().toString(), node);
        }

        // 第二次遍历：建立父子关系
        for (GoodsCategory category : allCategories) {
            String parentCode = category.getParent_code();
            CategoryTree currentNode = categoryMap.get(category.getCode().toString());

            if ("NULL".equals(parentCode)) {
                // 如果是根节点，直接添加到根列表
                rootList.add(currentNode);
            } else {
                // 如果不是根节点，添加到父节点的children中
                CategoryTree parentNode = categoryMap.get(parentCode);
                if (parentNode != null) {
                    parentNode.getChildren().add(currentNode);
                }
            }
        }

        return rootList;
    }

    //发布商品
    @Override
    public CustomResponse addNewGood(Good good, List<MultipartFile> goodsImages) throws IOException {
        try {
            // 设置默认值
            good.setTurnover("0");   //默认销量
            good.setIsOnline(0);    //默认待审核状态

            // 第一张图片作商品主图
            if (!goodsImages.isEmpty()) {
                // 使用新的路径上传主图
                String mainImageUrl = ossUtil.uploadImage(goodsImages.get(0), "product-img");
                // 提取文件名部分
//                String mainImageFileName = mainImageUrl.substring(mainImageUrl.lastIndexOf("/") + 1);
                good.setImg(mainImageUrl);
            }

            int result = goodsMapper.insert(good);
            if (result <= 0) {
                throw new RuntimeException("商品基本信息插入失败");
            }
            System.out.println("商品的ID号:"+good.getGid());   //测试

            // 上传其余商品图片并保存到t_goods_image表
            List<String> uploadedUrls = new ArrayList<>();
            for (MultipartFile goodsImage : goodsImages) {
                String imageUrl = ossUtil.uploadImage(goodsImage, "goodsImg");
                uploadedUrls.add(imageUrl);

                int imageResult = goodsMapper.insertGoodsImage(good.getGid(), imageUrl);
                if (imageResult <= 0) {
                    throw new RuntimeException("商品图片信息插入失败");
                }
            }

            return new CustomResponse(200, "商品添加成功", good);

        } catch (Exception e) {
            if (good.getImg() != null) {
                CompletableFuture.runAsync(() -> {
                    String filename = good.getImg().substring(OSS_BUCKET_URL.length());
                    ossUtil.deleteFiles(filename);
                }, taskExecutor);
            }

            return new CustomResponse(500, "商品添加失败：" + e.getMessage(), null);
        }
    }

    @Override
    public String identifyImgApi(MultipartFile file) throws IOException {
        return ossUtil.uploadImage(file, "identifyImg");
    }

        @Override
    @Transactional(rollbackFor = Exception.class)
    public CustomResponse deleteGood(Integer gid) {
        try{
            Good existgood = goodsMapper.selectById(gid);

            if(existgood != null){
                // 检查是否有相关订单项
                int orderItemCount = goodsMapper.countOrderItemsByGid(gid);
                log.info("商品ID {} 关联的订单项数量: {}", gid, orderItemCount);
                
                // 获取商品相关的图片URL列表
                List<String> imageUrls = goodsMapper.selectGoodsImagesByGid(gid);
                
                // 删除商品图片记录
                goodsMapper.deleteGoodsImages(gid);
                
                // 删除商品评价记录
                goodsMapper.deleteGoodsEvaluations(gid);
                
                // 删除相关订单项（注意：这会影响历史订单数据）
                if(orderItemCount > 0) {
                    goodsMapper.deleteOrderItemsByGid(gid);
                    log.warn("已删除商品ID {} 相关的 {} 个订单项", gid, orderItemCount);
                }
                
                // 删除商品记录（硬删除）
                int result = goodsMapper.deleteById(gid);
                
                if(result > 0) {
                    // 异步删除OSS中的图片文件
                    CompletableFuture.runAsync(() -> {
                        // 删除主图
                        if (existgood.getImg() != null) {
                            try {
                                String mainImgPath = existgood.getImg().substring(existgood.getImg().indexOf("/20"));
                                if (mainImgPath.startsWith("/")) {
                                    mainImgPath = mainImgPath.substring(1);
                                }
                                ossUtil.deleteFiles(mainImgPath);
                            } catch (Exception e) {
                                log.error("删除主图失败: {}", e.getMessage());
                            }
                        }
                        
                        // 删除其他图片
                        imageUrls.forEach(imageUrl -> {
                            try {
                                String filePath = imageUrl.substring(imageUrl.indexOf("/20"));
                                if (filePath.startsWith("/")) {
                                    filePath = filePath.substring(1);
                                }
                                ossUtil.deleteFiles(filePath);
                            } catch (Exception e) {
                                log.error("删除商品图片失败: {}", e.getMessage());
                            }
                        });
                    }, taskExecutor);
                    
                    return new CustomResponse(200,"商品删除成功",null);
                } else {
                    return new CustomResponse(500,"商品删除失败",null);
                }
            } else {
                return new CustomResponse(404,"商品不存在",null);
            }

        }catch (Exception e){
            log.error("删除商品异常: ", e);
            return new CustomResponse(500,"服务器出错！",null);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public CustomResponse updateGood(Good good, List<MultipartFile> files) throws IOException {
        try {
            // 验证输入
            if (good == null || good.getGid() == null) {
                return new CustomResponse(400, "无效输入", null);
            }

            // 查找现有商品
            Good existingGood = goodsMapper.selectById(good.getGid());
            if (existingGood == null) {
                return new CustomResponse(400, "未找到商品", null);
            }

            // 如果有新图片上传且不是空文件
            if (files != null && !files.isEmpty() && files.get(0).getSize() > 0) {
                // 1. 获取旧图片URL列表
                List<String> oldImageUrls = goodsMapper.selectGoodsImagesByGid(good.getGid());
                System.out.println("旧图片URLs: " + oldImageUrls); // 调试日志

                // 2. 删除数据库中的旧图片记录
                int deletedCount = goodsMapper.deleteGoodsImages(good.getGid());
                System.out.println("删除的图片记录数: " + deletedCount); // 调试日志

                // 3. 异步删除OSS中的旧图片
                CompletableFuture.runAsync(() -> {
                    oldImageUrls.forEach(oldUrl -> {
                        try {
                            // 从完整URL中提取文件路径
                            String filePath = oldUrl.substring(oldUrl.indexOf("/20"));
                            if (filePath.startsWith("/")) {
                                filePath = filePath.substring(1);
                            }
                            log.info("删除OSS文件路径: {}", filePath);
                            ossUtil.deleteFiles(filePath);
                        } catch (Exception e) {
                            log.error("删除OSS文件失败: {}", e.getMessage());
                        }
                    });
                }, taskExecutor);

                List<String> newImageUrls = new ArrayList<>();
                for (MultipartFile file : files) {
                    if (file.getSize() > 0) {
                        // 获取原始文件的扩展名
                        String originalFilename = file.getOriginalFilename();
                        String extension = "";
                        if (originalFilename != null && originalFilename.contains(".")) {
                            extension = originalFilename.substring(originalFilename.lastIndexOf("."));
                        } else {
                            extension = ".jpg"; // 默认扩展
                        }

                        // 上传图片并确保URL包含扩展名
                        String imageUrl = ossUtil.uploadImage(file, "goodsImg");
                        if (!imageUrl.endsWith(extension)) {
                            imageUrl += extension;
                        }

                        newImageUrls.add(imageUrl);
                        log.info("上传新图片: {}", imageUrl);

                        // 保存图片记录
                        int imageResult = goodsMapper.insertGoodsImage(good.getGid(), imageUrl);
                        if (imageResult <= 0) {
                            throw new RuntimeException("图片记录插入失败");
                        }
                    }
                }

                // 更新商品主图
                if (!newImageUrls.isEmpty()) {
                    String mainImageUrl = newImageUrls.get(0);
                    existingGood.setImg(mainImageUrl);
                    log.info("更新商品主图: {}", mainImageUrl);
                }
            }

            // 更新商品基本信息
            existingGood.setTitle(good.getTitle());
            existingGood.setG_price(good.getG_price());
            existingGood.setStock_quantity(good.getStock_quantity());
            existingGood.setTags(good.getTags());
            existingGood.setProvince(good.getProvince());
            existingGood.setCity(good.getCity());
            existingGood.setCategory(good.getCategory());
            existingGood.setIsOnline(good.getIsOnline());
            existingGood.setDescription(good.getDescription());

            int result = goodsMapper.updateById(existingGood);
            if (result <= 0) {
                throw new RuntimeException("商品基本信息更新失败");
            }

            return new CustomResponse(200, "商品信息更新成功", existingGood);
        } catch (Exception e) {
            log.error("更新商品失败: ", e);
            throw e;
        }
    }

    //评价信息
    @Override
    public String EvaluateProduct(GoodsEvaluation evaluation) {
        try {
            evaluation.setSend_date(new Timestamp(System.currentTimeMillis()));

            if (evaluation.getUid() == null || evaluation.getGid() == null ||
                evaluation.getStars() == null || evaluation.getEvaluation() == null) {
                return "评价信息不完整";
            }

            if (evaluation.getStars() < 1 || evaluation.getStars() > 5) {
                return "星级评分必须在1-5之间";
            }

            int result = goodsMapper.evaluateProduct(evaluation);
            if (result > 0) {
                return "评价成功";
            } else {
                return "评价失败";
            }
        } catch (Exception e) {
            log.error("商品评价失败: ", e);
            return "系统错误，评价失败";
        }
    }

    @Override
    public List<GoodsEvaluation> getProductEvaluate(Integer gid) {
        try {
            return goodsMapper.getProductEvaluate(gid);
        } catch (Exception e) {
            log.error("获取商品评价失败: ", e);
            return new ArrayList<>();
        }
    }
    
    @Override
    public int countGoodsByShopId(Integer shopId) {
        QueryWrapper<Good> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("shop_id", shopId);
        return Math.toIntExact(goodsMapper.selectCount(queryWrapper));
    }
    
    @Override
    public List<Map<String, Object>> getGoodsSalesRanking(Integer shopId) {
        return goodsMapper.selectGoodsSalesRanking(shopId);
    }
}